package org.asiainfo.common.mybatis.stream.core.page;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.Data;
import org.asiainfo.common.core.utils.StringUtils;

import java.io.Serial;
import java.io.Serializable;

/**
 * 分页查询实体类
 *
 * @author dotor-ww
 */
@Data
public class PageQuery implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 分页大小
     */
    private Integer pageSize;

    /**
     * 当前页数
     */
    private Integer pageNum;

    /**
     * 排序列
     */
    private String orderBy;

    /**
     * 排序的方向desc或者asc 默认值desc
     */
    private String orderType = "desc";

    /**
     * 当前记录起始索引 默认值
     */
    public static final int DEFAULT_PAGE_NUM = 1;

    /**
     * 每页显示记录数 默认值 默认查全部
     */
    public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE;

    /**
     * 构建分页对象
     */
    public <T> Page<T> buildPage() {
        Integer pageNum = ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM);
        Integer pageSize = ObjectUtil.defaultIfNull(getPageSize(), DEFAULT_PAGE_SIZE);
        if (pageNum <= 0) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        return new Page<>(pageNum, pageSize);
    }

    /**
     * 构建排序
     */
    public void buildOrder(QueryWrapper query) {
        if (StringUtils.isEmpty(orderBy)) {
            return;
        }
        query.orderBy(StringUtils.toUnderScoreCase(orderBy), StringUtils.equals(orderType, "asc"));
    }
}
